package me.keiwu.pub.util;

import me.keiwu.pub.data.GlobalConst;
import me.keiwu.pub.data.Token;
import me.keiwu.pub.util.redis.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.UUID;

/**
 * Created by kei on 12/09/2017.
 */
@Component
public class TokenUtil {


    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 授权token
     * @param userId
     * @return
     */
    public Token createAccessToken(long userId) {
        String token = UUID.randomUUID().toString().replace("-", "") + "-" + userId;
        redisUtil.set(GlobalConst.ACCESS_TOKEN_PREFIX + userId, token, GlobalConst.EXPIRED_TWO_HOURS_SECONDS);
        long expiredAt = new Timestamp(System.currentTimeMillis() + GlobalConst.EXPIRED_TWO_HOURS_SECONDS * 1000L).getTime();
        return new Token(userId, token, expiredAt);
    }


    /**
     * 通用token
     * @param userId
     * @param append
     * @param prefix
     * @param expireSecs
     * @return
     */
    public Token createCommonToken(long userId, String append, String prefix, int expireSecs) {
        String token = UUID.randomUUID().toString().replace("-", "") + "-" + append;
        redisUtil.set(prefix + append, token, expireSecs);
        long expiredAt = new Timestamp(System.currentTimeMillis() + expireSecs * 1000L).getTime();
        return new Token(userId, token, expiredAt);
    }

    /**
     * 更新token
     * @param userId
     * @param token
     */
    public Token updateAccessToken(long userId, String token) {
        redisUtil.set(GlobalConst.ACCESS_TOKEN_PREFIX + userId, token, GlobalConst.EXPIRED_TWO_HOURS_SECONDS);
        long expiredAt = new Timestamp(System.currentTimeMillis() + GlobalConst.EXPIRED_TWO_HOURS_SECONDS * 1000L).getTime();
        return new Token(userId, token, expiredAt);
    }

    /**
     * 获取 access_token
     * @param userId
     * @return
     */
    public String getAccessToken(long userId) {
        return redisUtil.get(GlobalConst.ACCESS_TOKEN_PREFIX + userId);
    }


    /**
     * 获取token
     * @param key prefix+append
     * @return
     */
    public String getCommonToken(String key) {
        return redisUtil.get(key);
    }


    /**
     * 通过token解析userId
     * @param token
     * @return
     */
    public static Long parseUserId(String token) {
        String key = parseKey(token);
        if (key == null) return null;
        return Long.valueOf(key);
    }

    /**
     * 通过token解析key
     * @param token
     * @return
     */
    public static String parseKey(String token) {
        if (StringUtils.isBlank(token)) return null;
        String[] str = token.split("-");
        if (str.length < 2) return null;
        return str[1];
    }


    /**
     * 检查access_token
     * @param accessToken
     * @return
     */
    public boolean checkAccessToken(String accessToken) {
        logger.info("checkAccessToken accessToken={}", accessToken);
        if (StringUtils.isBlank(accessToken)) return false;
        Long userId = parseUserId(accessToken);
        String rToken = redisUtil.get(GlobalConst.ACCESS_TOKEN_PREFIX + userId);
        return accessToken.equals(rToken);
    }


}
